import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author gao
 * @date 2025/8/19 14:35
 */

public class EchoServer {
    private ServerSocket serverSocket;

    public EchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true) {
            // 如果客户端没有建立连接就会阻塞
            Socket socket = serverSocket.accept();
            Thread t = new Thread(() ->{
                processConnection(socket);
            });
            t.start();
        }
    }

    /**
    * 处理客户端连接的方法
    * @param socket 客户端套接字对象，用于与客户端进行通信
    */
    private void processConnection(Socket socket) {
        System.out.printf("[%s:%d] 客户端上线!\n", socket.getInetAddress().toString(), socket.getPort());
        try (InputStream inputStream = socket.getInputStream();  // 从socket获取输入流，用于读取客户端发送的数据
              OutputStream outputStream = socket.getOutputStream()) {
            Scanner in = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                // 读取请求并解析
                if (!in.hasNext()) {
                    // 针对客户端下线的逻辑，比如客户端结束了
                    System.out.printf("[%s:%d] 客户端下线!\n", socket.getInetAddress().toString(), socket.getPort());
                    break;
                }
                System.out.println("服务器收到了数据");
                String request = in.next();
                // 根据请求计算响应
                String response = process(request);
                // 把响应写回到客户端
                writer.println(response);
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理请求字符串的方法
     * 该方法接收一个字符串参数，直接返回该参数
     *
     * @param request 需要处理的字符串请求
     * @return 返回与输入相同的字符串
     */
    private String process(String request) {
    // 直接返回输入的请求字符串
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer server = new EchoServer(9090);
        server.start();
    }
}